import { getMpList, MpVO } from '@/services/MpService'
import { createQrCode } from '@/services/qrCodeService'
import { getSocialUserTagList } from '@/services/SocialUserTagService'
import { makeAutoObservable, runInAction, when } from 'mobx'
import { QrCodeUpdateBO, QrCodeUpdateDTO, QrCodeVO, QrType } from '../../types/qrCode'
import { SocialUserTag } from '../../types/tag'

class QrCodeModel {
  updateModalState = false
  currentQrCode?: QrCodeUpdateBO
  socialUserTagList: SocialUserTag[] = []
  mpList: MpVO[] = []

  constructor() {
    makeAutoObservable(this, {}, { autoBind: true })
    when(
      () => this.updateModalState,
      () => {
        this.getSocialUserTagList().then()
        this.getMpList().then()
      },
    )
  }

  edit(vo: QrCodeVO) {
    this.updateModalState = true
    this.currentQrCode = {
      isLast: vo.expireTime === undefined,
      mpType: vo.appType,
      appId: vo.appId,
      expireTime: vo.expireTime,
      isSystemCreated: false,
      id: vo.id,
      describe: vo.describe,
      type: vo.type,
      bindTagIds: vo.autoBindTags.map((value) => value.id),
      messagePocketId: vo.messagePocketId,
    }
  }

  async save(bo: QrCodeUpdateBO) {
    let type: QrType = 'wx_mp_temp'
    if (bo.mpType === 'wx_miniapp') {
      type = 'wx_miniapp'
    } else if (bo.isLast) {
      type = 'wx_mp'
    }
    let dto: QrCodeUpdateDTO = {
      id: bo.id,
      appId: bo.appId,
      bindTagIds: bo.bindTagIds,
      describe: bo.describe,
      expireTime: bo.isLast ? undefined : bo.expireTime,
      isSystemCreated: false,
      messagePocketId: bo.messagePocketId,
      type: type,
    }
    let resp = await createQrCode(dto)
    return resp !== null
  }

  get socialUserTagListEnum() {
    return this.socialUserTagList.map((value) => ({ label: value.tagName, value: value.id }))
  }

  get mpListEnum() {
    return this.mpList.map((value) => ({ label: value.nickName, value: value.appId, type: value.registerType }))
  }

  get isUpdate() {
    return this.currentQrCode?.id !== undefined
  }

  setUpdateModalState(state: boolean) {
    this.updateModalState = state
  }

  async getSocialUserTagList() {
    let tags = await getSocialUserTagList()
    runInAction(() => (this.socialUserTagList = tags))
  }

  async getMpList() {
    let mpList = await getMpList({})
    runInAction(() => (this.mpList = mpList))
  }

  getMpInfo(appId: string): MpVO | undefined {
    return this.mpList.find((value) => value.appId === appId)
  }

  createQr() {
    this.currentQrCode = undefined
    this.updateModalState = true
  }
}

export default QrCodeModel
export const qrCodeModel = new QrCodeModel()
